package com.cu.employmentmanagementsystem.common.aop;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class LogAspect
{
    private static String USER_ID;
    private static final Logger LOGGER = Logger.getLogger(LogAspect.class);

    @Pointcut("execution(* com.cu.employmentmanagementsystem.controller.*.*(..))")
    public void allServiceMethodsPointcut()
    {

    }

    @Before("allServiceMethodsPointcut()")
    public void logBefore(JoinPoint joinPoint)
    {
        try
        {
            USER_ID = StpUtil.getLoginIdAsString();
        }
        catch (NotLoginException e)
        {
            USER_ID = "未知";
        }
        LOGGER.info("用户" + USER_ID + "调用方法：" + joinPoint.getSignature().toShortString() + "\n调用方法入参：" + Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(pointcut = "allServiceMethodsPointcut()", returning = "result")
    public void logAfterReturning(JoinPoint joinPoint, Object result)
    {
        if (result == null)
        {
            return;
        }
        Class<?> clazz = result.getClass();
        if (clazz == String.class)
        {
            String resultStr = ((String) result).substring(0, ((String) result).length() > 1000 ? 5000 : ((String) result).length());
            LOGGER.info("用户" + USER_ID + "方法返回：" + resultStr);
            return;
        }
        LOGGER.info("用户" + USER_ID + "方法返回：" + result);
    }

    @AfterThrowing(pointcut = "allServiceMethodsPointcut()", throwing = "exception")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable exception)
    {
        LOGGER.error("用户" + USER_ID + "所调用方法：" + joinPoint.getSignature().toShortString() + "抛出异常，\n异常信息：" + exception.getMessage());
    }

    @After("allServiceMethodsPointcut()")
    public void logAfter(JoinPoint joinPoint)
    {
        LOGGER.info("用户" + USER_ID + "调用方法：" + joinPoint.getSignature().toShortString() + "执行完毕");
    }
}
